package com.itheima.aop;


import com.itheima.mapper.OperateLoginMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
public class OperateLoginAspect {
    private static final Logger log = LoggerFactory.getLogger(OperateLoginAspect.class);
    @Autowired
    private OperateLoginMapper operateLoginMapper;

    @Pointcut("execution(* com.itheima.controller.LoginController.login(..))")
    public void loginPointCut() {
    }

    @Around("loginPointCut()")
    public Object recordLoginLog(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("记录登录日志开始");
        // --- 1. 在方法执行前 ---
        long startTime = System.currentTimeMillis();
        EmpLoginLog loginLog = new EmpLoginLog();
        loginLog.setLoginTime(LocalDateTime.now());
        // 获取方法参数 (用户名和密码)
        Object[] args = joinPoint.getArgs();
        Emp emp = (Emp) args[0];
        loginLog.setUsername(emp.getUsername());
        loginLog.setPassword(emp.getPassword());
        Object result = null;
        try {
            result = joinPoint.proceed();
            // 假设登录成功返回的Result对象中，code为1，data是一个包含token的Map
            if (result instanceof Result) {
                Result loginResult = (Result) result;
                if (loginResult.getCode() == 1) {
                    loginLog.setIsSuccess((short) 1);
                }
                loginLog.setJwt(loginResult.getData().toString());
            }
            return result;
        } catch (Exception e) {
            // --- 4. 如果方法抛出异常 (登录失败) ---
            loginLog.setIsSuccess((short) 0);
            log.error("登录异常", e);
            throw e;

        } finally {
            // 无论成功或失败，最后都执行 ---
            // 计算耗时
            long costTime = System.currentTimeMillis() - startTime;
            loginLog.setCostTime(costTime);

            // 保存日志到数据库
            operateLoginMapper.insert(loginLog);
            log.info("登录日志记录完毕，耗时: {}ms", loginLog.getCostTime());
            log.info("====== 结束记录登录日志 ======\n");
        }
    }
}
